<template>
  <div class="mb-10px">
    <div class="flex justify-between">
      <div class="font-size-16px font-600">{{ hasMany.label }}</div>
      <el-button type="primary" @click="add">+</el-button>
    </div>
    <el-table :data="data" highlight-current-row>
      <el-table-column v-for="(column, i) in hasMany.columns" :label="column.label" :key="i">
        <template #default="{ row }">
          <el-input v-model="row[camelCase(column.name)]" :placeholder="`请输入${column.label}`" :disabled="row._removed" />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <template v-if="Object.keys(crosses).length > 0">
            <el-button v-for="(item, cross) in crosses" :key="cross" @click="showData(row[cross], item)">
              {{ item.label }}({{ item.type == 'hasMany' ? row[cross]?.length : (row[cross] ? 1 : 0) }})
            </el-button>
          </template>
          <el-button v-else type="danger" @click="remove(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<script setup lang="ts">
  import { ElTable, ElTableColumn, ElInput, ElButton } from 'element-plus'
  import { Cross } from '@/seed-application/types'
  import { popup } from '@/components/Popup'
  import { h } from 'vue'
  import { camelCase } from 'lodash-es'
  import UpdateList from './UpdateList.vue'
  import Update from './Update.vue'
  import { initData } from '@/seed-application/utils/SeedUtil'

  const props = defineProps<{hasMany: Cross, data: any[]}>()
  const hasMany = props.hasMany
  const data = props.data
  const crosses = hasMany.crosses

  const add = () => data.push(initData({}, hasMany.columns, hasMany.crosses))

  const remove = (row) => data.splice(data.findIndex(e => e == row), 1)

  const showData = (data: any, cross: Cross) => {
    popup({ title: cross.label }, {
      default: () => {
        if(cross.type == 'hasMany') return h(UpdateList, {hasMany: cross, data})
        return h(Update, {hasOne: cross, data})
      }
    })
  }
</script>